package site.laodengtou.controller;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.swing.JOptionPane;
import javax.swing.JPanel;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import io.swagger.annotations.ApiOperation;
import site.laodengtou.pojo.Question;
import site.laodengtou.pojo.Test;
import site.laodengtou.pojo.Works;
import site.laodengtou.service.StudentService;
import site.laodengtou.util.CustomStringJavaCompiler;
import site.laodengtou.util.Msg;

@Controller
public class StudentController {

	@Autowired
	StudentService studentService;

	/**
	 * 考生登录
	 * 
	 * @param ksh      考生号
	 * @param password 考生密码
	 * @return
	 */
	@RequestMapping(value = "stulogin", method = RequestMethod.GET)
	public String stuLogin(String ksh, String password, HttpServletRequest req) {
		Msg msg;
		msg = studentService.selStuCountByLogin(ksh, password);
		if (msg.getCode() == 100) {
			req.getSession().setAttribute("student", ksh);
			return "index";
		} else {
			return "login";
		}
	}

	/**
	 * 查询考试
	 * 
	 * @return
	 */
	@RequestMapping(value = "selworks", method = RequestMethod.GET)
	public ModelAndView selWorks() {
		List<Works> list = studentService.selWorks();
		ModelAndView model = new ModelAndView();
		model.addObject("works", list);
		model.setViewName("works");
		return model;
	}

	/**
	 * 随机抽取5道题目，形成试卷,获取该考试该学生的提交信息
	 * 
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "test", method = RequestMethod.GET)
	public ModelAndView selWord(int workid, String worktitle,HttpServletRequest req) {
		ModelAndView mav = new ModelAndView();
		if (req.getSession().getAttribute("student") == null) {
			mav.setViewName("login");
			return mav;
		} else {

			List<Question> questions = studentService.getQuestions();// 获取5道题

			List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
			String khs = req.getSession().getAttribute("student").toString();
			System.out.println("考生号" + khs);
			Test test = new Test();// 实例话试卷实体类
			for (int i = 0; i < questions.size(); i++) {
				System.out.println("控制器生产的题目id" + questions.get(i).getId());
				if (i == 0) {
					test.setQuestionid1(questions.get(i).getId());
				} else if (i == 1) {
					test.setQuestionid2(questions.get(i).getId());
				} else if (i == 2) {
					test.setQuestionid3(questions.get(i).getId());
				} else if (i == 3) {
					test.setQuestionid4(questions.get(i).getId());
				} else if (i == 4) {
					test.setQuestionid5(questions.get(i).getId());
				}
				test.setWorkid(workid);
			}
			int j = studentService.insTest(test);
			System.out.println("生产试卷的id"+j);

			for (int i = 0; i < questions.size(); i++) {
				Map<String, Object> map = new HashMap<String, Object>();
				int passcount = studentService.selCountPassQuestion(questions.get(i).getId(), khs);
				int subcount = studentService.selCountSubmitQuestion(questions.get(i).getId(), khs);
				int maxgrade = studentService.selMaxGradeQuestion(questions.get(i).getId(), khs);
				map.put("describe", questions.get(i).getDescribes());
				map.put("pass", passcount);
				map.put("sub", subcount);
				map.put("maxgrade", maxgrade);
				map.put("questionid", questions.get(i).getId());
				map.put("workid", workid);
				
				list.add(map);
			}

			mav.addObject("questions", list);
			mav.addObject("workid", workid);
			mav.setViewName("test");
			mav.addObject("testid", j);
			mav.addObject("worktitle",worktitle);
			return mav;
		}

	}

	/**
	 * 获取答题信息控制器
	 * 
	 * @param questionid
	 * @return
	 */
	@RequestMapping(value = "dati", method = RequestMethod.GET)
	public ModelAndView dati(int questionid, int workid, int testid,String worktitle) {
		Question question = studentService.selQuestionByid(questionid);
		ModelAndView mav = new ModelAndView();
		mav.addObject("question", question);
		mav.addObject("workid", workid);
		mav.addObject("testid", testid);
		mav.setViewName("dati");
		mav.addObject("worktitle",worktitle);

		return mav;
	}

	/**
	 * 进入提交代码页面
	 * 
	 * @param questionid
	 * @return
	 */
	@RequestMapping(value = "subcode", method = RequestMethod.POST)
	public ModelAndView subcode(String worktitle,int questionid, int workid, int testid) {
		ModelAndView mav = new ModelAndView();
		mav.addObject("questionid", questionid);
		mav.addObject("workid", workid);
		mav.addObject("testid", testid);
		mav.setViewName("subcode");
		mav.addObject("worktitle",worktitle);
		return mav;
	}

	/**
	 * 学生提交代码
	 */
	@RequestMapping(value = "submitcode", method = RequestMethod.POST)
	public ModelAndView submitcode(int workid, int questionid,String worktitle, String code, int testid, HttpServletRequest req) {

		ModelAndView mav = new ModelAndView();
		if (req.getSession().getAttribute("student") == null) {
			JOptionPane.showMessageDialog(null, "请先登录", "系统提示", JOptionPane.PLAIN_MESSAGE);
			mav.setViewName("login");
			return mav;
		} else {
			String ksh = req.getSession().getAttribute("student").toString();
			int i = studentService.insSubmitcode(workid, questionid, ksh, code);
			if (i == 1) {
				JOptionPane.showMessageDialog(null, "提交成功", "系统提示", JOptionPane.PLAIN_MESSAGE);
				System.out.println("获取问题id"+testid);
				Test test = studentService.selTestById(testid);
				Question question1 = studentService.selQuestionByid(test.getQuestionid1());
				Question question2 = studentService.selQuestionByid(test.getQuestionid2());
				Question question3 = studentService.selQuestionByid(test.getQuestionid3());
				Question question4 = studentService.selQuestionByid(test.getQuestionid4());
				Question question5 = studentService.selQuestionByid(test.getQuestionid5());

				List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();

				Map<String, Object> map = new HashMap<String, Object>();
				int passcount = studentService.selCountPassQuestion(question1.getId(), ksh);
				int subcount = studentService.selCountSubmitQuestion(question1.getId(), ksh);
				int maxgrade = studentService.selMaxGradeQuestion(question1.getId(), ksh);
				map.put("describe", question1.getDescribes());
				map.put("pass", passcount);
				map.put("sub", subcount);
				map.put("maxgrade", maxgrade);
				map.put("questionid", question1.getId());
				map.put("workid", workid);
				list.add(map);

				Map<String, Object> map1 = new HashMap<String, Object>();
				int passcount1 = studentService.selCountPassQuestion(question2.getId(), ksh);
				int subcount1 = studentService.selCountSubmitQuestion(question2.getId(), ksh);
				int maxgrade1 = studentService.selMaxGradeQuestion(question2.getId(), ksh);
				map1.put("describe", question2.getDescribes());
				map1.put("pass", passcount1);
				map1.put("sub", subcount1);
				map1.put("maxgrade", maxgrade1);
				map1.put("questionid", question2.getId());
				map1.put("workid", workid);
				list.add(map1);

				Map<String, Object> map2 = new HashMap<String, Object>();
				int passcount2 = studentService.selCountPassQuestion(question3.getId(), ksh);
				int subcount2 = studentService.selCountSubmitQuestion(question3.getId(), ksh);
				int maxgrade2 = studentService.selMaxGradeQuestion(question3.getId(), ksh);
				map2.put("describe", question3.getDescribes());
				map2.put("pass", passcount2);
				map2.put("sub", subcount2);
				map2.put("maxgrade", maxgrade2);
				map2.put("questionid", question3.getId());
				map2.put("workid", workid);
				list.add(map2);

				Map<String, Object> map3 = new HashMap<String, Object>();
				int passcount3 = studentService.selCountPassQuestion(question4.getId(), ksh);
				int subcount3 = studentService.selCountSubmitQuestion(question4.getId(), ksh);
				int maxgrade3 = studentService.selMaxGradeQuestion(question4.getId(), ksh);
				map3.put("describe", question4.getDescribes());
				map3.put("pass", passcount3);
				map3.put("sub", subcount3);
				map3.put("maxgrade", maxgrade3);
				map3.put("questionid", question4.getId());
				map3.put("workid", workid);
				list.add(map3);

				Map<String, Object> map4 = new HashMap<String, Object>();
				int passcount4 = studentService.selCountPassQuestion(question5.getId(), ksh);
				int subcount4 = studentService.selCountSubmitQuestion(question5.getId(), ksh);
				int maxgrade4 = studentService.selMaxGradeQuestion(question5.getId(), ksh);
				map4.put("describe", question5.getDescribes());
				map4.put("pass", passcount4);
				map4.put("sub", subcount4);
				map4.put("maxgrade", maxgrade4);
				map4.put("questionid", question5.getId());
				map4.put("workid", workid);
				list.add(map4);

				mav.addObject("questions", list);
				mav.addObject("workid", workid);
				mav.setViewName("test");
				mav.addObject("testid", testid);
				mav.addObject("worktitle",worktitle);
				return mav;

			} else {
				JOptionPane.showMessageDialog(null, "提交失败", "系统提示", JOptionPane.PLAIN_MESSAGE);
				return null;
			}
		}
	}
	
	
	@RequestMapping(value="bianyi",method=RequestMethod.GET)
	public void bianyi(String code,HttpServletResponse response) {
		   System.out.println("代码："+code);
		    try {
				String newcode = URLDecoder.decode(code,"utf-8");
				  String code1 = "";
				    CustomStringJavaCompiler compiler = new CustomStringJavaCompiler(newcode);
			        boolean res = compiler.compiler();
			        if (res) {
			        	code1+="编译成功\n";
			        	code1+="compilerTakeTime：" + compiler.getCompilerTakeTime()+"\n";
			            try {
			                compiler.runMainMethod();
			                code1+="runTakeTime：" + compiler.getRunTakeTime()+"\n";
			            } catch (Exception e) {
			                e.printStackTrace();
			            }
			            code1+="runTakeTime：" + compiler.getRunTakeTime()+"\n";
			            code1+="诊断信息：" + compiler.getCompilerMessage()+"\n";
			        } else {
			        	code1+="编译失败";
			            code1+=compiler.getCompilerMessage()+"\n";
			        }
			        response.setContentType("text/plain; charset=utf-8");
				    try {
						Writer writer = response.getWriter();
						writer.write(code1);
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}		 
			} catch (UnsupportedEncodingException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
		    
	      
	}
}
